package dice.sinanya.db.attr;

import dice.sinanya.db.tools.DbUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

import static dice.sinanya.system.MessagesAttr.customAttrList;

/**
 * @author SitaNya
 * 日期: 2019-08-07
 * 电子邮箱: sitanya@qq.com
 * 维护群(QQ): 162279609
 * 有任何问题欢迎咨询
 * 类说明:
 */
public class SelectAttr {
    private static final Logger log = LogManager.getLogger(SelectAttr.class.getName());


    /**
     * 读取数据库中的骰点历史信息到缓存
     */
    public void flushAttrList() {
        customAttrList.clear();
        try (Connection conn = DbUtil.getConnection()) {
            String sql = "select * from test.customAttr";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                try (ResultSet set = ps.executeQuery()) {
                    while (set.next()) {
                        long groupId = set.getLong("groupId");
                        String attrName = set.getString("attrName");
                        String function = set.getString("function");
                        HashMap<String, String> attrList = customAttrList.getOrDefault(groupId, new HashMap<>());
                        attrList.put(attrName, function);
                        customAttrList.put(groupId, attrList);
                    }
                }
            }
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }
}
